package org.platform.lwc.redis.factory.redission;

import org.platform.lwc.redis.utils.ConvertUtil;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

public class SentinelRedissonClient implements IRedissonClient {
    @Override
    public RedissonClient getRedissonClient(RedisProperties redisProperties) {
        // 哨兵配置
        Method nodesMethod = ReflectionUtils.findMethod(RedisProperties.Sentinel.class, "getNodes");
        Object nodesValue = ReflectionUtils.invokeMethod(nodesMethod, redisProperties.getSentinel());
        String[] nodes;
        if (nodesValue instanceof String) {
            nodes = ConvertUtil.convert(Arrays.asList(((String) nodesValue).split(",")));
        } else {
            nodes = ConvertUtil.convert((List<String>) nodesValue);
        }
        Config config = new Config();
        config.useSentinelServers()
                .setMasterName(redisProperties.getSentinel().getMaster())
                .addSentinelAddress(nodes)
                .setDatabase(redisProperties.getDatabase())
                .setConnectTimeout(ConvertUtil.getConnectTimeout(redisProperties))
                .setPassword(redisProperties.getPassword());
        return Redisson.create(config);
    }


}
